package com.yitongmao.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.bean.RegisterVerificationcodeBean;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.util.MD5Builder;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.R;

import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

public class RegisterActivity extends AppCompatActivity {
    private boolean flag = true;
    private Button mZhuCeNext;
    private Button mZhuCe;
    private LinearLayout zhucehuitui;
    private EditText et_activity_login_phone;
    private EditText et_activity_login_yanzhengma;
    private EditText et_ctivitylogin_password;
    private EditText et_ctivity_login_yaoqingma;
    private TextView mVerificationcode;
    private ImageView myRead;
    private TimeCount time;
    private String phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        immerSion();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        time = new TimeCount(60000, 1000);
        initView();
        setOnClick();
    }

    //设置监听事件
    private void setOnClick() {
        mZhuCe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = et_activity_login_phone.getText().toString().trim();
                String code = et_activity_login_yanzhengma.getText().toString().trim();
                String pwd = et_ctivitylogin_password.getText().toString().trim();
                String inviteCode = et_ctivity_login_yaoqingma.getText().toString().trim();
                if (!flag) {
                    if (pwd.length() < 6 || pwd.length() > 20) {
                        ToastUtils.showShort(RegisterActivity.this, "密码格式有误");
                    } else {
                        registerOne(userName, code, pwd, inviteCode);
                    }
                } else {
                    ToastUtils.showShort(RegisterActivity.this, "必须同意用户协议才能注册哦");
                }
            }
        });

        mVerificationcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = et_activity_login_phone.getText().toString().trim();
                if (phone != null && phone.length() <= 11) {
                    sendVerificationcode(phone);
                } else {
                    ToastUtils.showShort(RegisterActivity.this, "手机格式错误！");
                }
            }
        });
        myRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag) {
                    myRead.setImageResource(R.drawable.zhucexieyidianji);
                    flag = false;
                } else {
                    myRead.setImageResource(R.drawable.zhucexieyimeiyoudianji);
                    flag = true;
                }
            }
        });
    }

    //初始化控件
    private void initView() {
        //监听edittext的输入状态
        TextChange textChange = new TextChange();
        et_activity_login_phone = (EditText) findViewById(R.id.et_activity_login_phone);
        et_activity_login_yanzhengma = (EditText) findViewById(R.id.et_activity_login_yanzhengma);
        et_ctivitylogin_password = (EditText) findViewById(R.id.et_ctivitylogin_password);
        et_ctivity_login_yaoqingma = (EditText) findViewById(R.id.et_ctivity_login_yaoqingma);
        et_activity_login_phone.addTextChangedListener(textChange);
        et_activity_login_yanzhengma.addTextChangedListener(textChange);
        et_ctivitylogin_password.addTextChangedListener(textChange);
        et_ctivity_login_yaoqingma.addTextChangedListener(textChange);
        mZhuCeNext = (Button) findViewById(R.id.mZhuCeNext);
        mZhuCe = (Button) findViewById(R.id.mZhuCe);
        zhucehuitui = (LinearLayout) findViewById(R.id.zhucehuitui);
        mVerificationcode = (TextView) findViewById(R.id.mVerificationcode1);
        zhucehuitui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.this.finish();
            }
        });
        myRead = (ImageView) findViewById(R.id.myRead);
    }

    //沉浸式状态栏
    public void immerSion() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.BLACK);
        }
    }

    //设置edittext的输入监听
    class TextChange implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (et_activity_login_phone.length() > 0 && et_activity_login_yanzhengma.length() > 0 && et_ctivitylogin_password.length() > 0 && et_ctivity_login_yaoqingma.length() > 0) {
                mZhuCeNext.setVisibility(View.GONE);
                mZhuCe.setVisibility(View.VISIBLE);
               /* if (et_activity_login_phone.length()<11){

                }*/
            }
        }
    }

    //获取验证码
    public void sendVerificationcode(final String phone) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("phone", phone);
        params.put("type", "register");
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.registerUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                String string = (String) result;
                Log.e("Gson", "" + string);
                Gson gson = new Gson();
                RegisterVerificationcodeBean registerVerificationcodeBean = gson.fromJson(string, RegisterVerificationcodeBean.class);
                if (registerVerificationcodeBean.result.state.equals("1")) {
                    time.start();
                } else {
                    ToastUtils.showShort(RegisterActivity.this, "" + registerVerificationcodeBean.result.message);
                }
            }

            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }

    //注册第一步完成
    public void registerOne(final String userName, final String code, final String pwd, final String inviteCode) {
        MD5Builder md5Builder = new MD5Builder();
        String password = md5Builder.getMD5Str(pwd);
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userName", userName);
        params.put("pwd", password);
        params.put("code", code);
        params.put("inviteCode", inviteCode);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.registerOneUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                Log.e("zzz", "" + result);
                String string = (String) result;
                Gson gson = new Gson();
                RegisterVerificationcodeBean registerVerificationcodeBean = gson.fromJson(string, RegisterVerificationcodeBean.class);
                if (registerVerificationcodeBean.result.state.equals("1")) {
                    Intent intent = new Intent(RegisterActivity.this, RegisterTwoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("userName", userName);
                    bundle.putString("code", code);
                    bundle.putString("pwd", pwd);
                    bundle.putString("inviteCode", inviteCode);
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    ToastUtils.showShort(RegisterActivity.this, "" + registerVerificationcodeBean.result.message);
                }
            }

            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }

    //监听输入框
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            mVerificationcode.setText("获取验证码");
            mVerificationcode.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            mVerificationcode.setClickable(false);//防止重复点击
            mVerificationcode.setText(millisUntilFinished / 1000 + "S");
        }
    }
}
